package com.lingyue.commons.zlib;

import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;

import java.io.*;
import java.util.Arrays;
import java.util.zip.GZIPOutputStream;

/**
 * @author king
 */
@Slf4j
public class GzipUtils {
    /**
     * 压缩文件成Gzip格式，Linux上可使用 压缩文件夹生成后缀名为".gz"的文件并下载
     *
     */
    public static File compressFolder(String folderPath, String gzipFileName) {
        File srcPath = new File(folderPath);
        int length = srcPath.listFiles().length;
        log.info("当前文件数：{}", length);
        // 设定读入缓冲区尺寸
        byte[] buf = new byte[1024];
        File[] files = srcPath.listFiles();
        String gzipFilePath = new StringBuffer().append(srcPath.getPath()).append(File.separator).append(gzipFileName).toString();
        String tarFile = new StringBuffer().append(gzipFilePath).append(".tar").toString();
        String gzipFile = new StringBuffer().append(gzipFilePath).append(".gz").toString();
        try {
            // 建立压缩文件输出流
            @Cleanup
            FileOutputStream fout = new FileOutputStream (tarFile);
            // 建立tar压缩输出流
            @Cleanup
            TarArchiveOutputStream tout = new TarArchiveOutputStream (fout);
            for(File file: files){
                String name = file.getName();
                String fileName = new StringBuffer().append(srcPath.getPath()).append(File.separator).append(name).toString();
                // 打开需压缩文件作为文件输入流
                // fileName是文件全路径
                @Cleanup
                FileInputStream fin = new FileInputStream (fileName);
                // 此处必须使用new
                TarArchiveEntry tarEn = new TarArchiveEntry (file);
                // 此处需重置名称，默认是带全路径的，否则打包后会带全路径
                tarEn.setName(name);
                tout.putArchiveEntry (tarEn);
                int num;
                while ((num = fin.read(buf, 0, 1024)) != -1) {
                    tout.write(buf, 0, num);
                }
                tout.closeArchiveEntry();
            }
            // 建立压缩文件输出流
            @Cleanup
            FileOutputStream gzFileStream = new FileOutputStream (gzipFile);
            // 建立gzip压缩输出流
            @Cleanup
            GZIPOutputStream gzout = new GZIPOutputStream (gzFileStream);
            // 打开需压缩文件作为文件输入流
            // gzipFilePath是文件全路径
            @Cleanup
            FileInputStream tarin = new FileInputStream (tarFile);
            int len;
            while ((len = tarin.read (buf, 0, 1024)) != -1) {
                gzout.write (buf, 0, len);
            }
        } catch (FileNotFoundException e) {
            log.error("压缩文件失败！失败原因：{}", e.getMessage());
        } catch (IOException e) {
            log.error("压缩文件失败！失败原因：{}", e.getMessage());
        } finally {
            File gzip = new File(gzipFile);
            File newFile = new File(gzipFilePath);
            boolean rename = gzip.renameTo(newFile);
            log.info("文件[{}]重命名为[{}], 状态：{}",gzip.getAbsolutePath(), newFile.getAbsolutePath(), rename);
            gzip.delete();
            File tar = new File(tarFile);
            tar.delete();
            return newFile;
        }
    }


    public static void main(String[] args) {
        GzipUtils.compressFolder("D:\\data\\dms_apps\\csvExport","LC192612.74010007.YYCRMNOTSPEC");
    }
}
